package exer;
/**
 * @title: ProductTest
 * @Author: wangzijun
 * @description:
 * @version: 1.0.0
 * @CreateTime: 2022-07-21  18:00
 */
class Clerk{
    private int productCount=0;

    public synchronized void product(){
        if(productCount<20){
            productCount++;

            System.out.println(Thread.currentThread().getName()+":开始生产第"+productCount+":个产品");
            notify();
        }else{
            try {
                wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public synchronized void consume() {
        if(productCount>0){
            System.out.println(Thread.currentThread().getName()+":开始消费第"+productCount+":个产品");
            productCount--;
            notify();
        }else{
            try{
                wait();
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }
    }
}
class Productor extends Thread{
    private Clerk clerk;
    public Productor(Clerk clerk){
        this.clerk=clerk;
    }

    @Override
    public void run() {
        super.run();
        System.out.println(Thread.currentThread().getName()+":开始生产产品........");

        while(true){
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            clerk.product();
        }

    }

}
class Consumer extends Thread{
    private  Clerk clerk;
    public Consumer(Clerk clerk){
        this.clerk=clerk;
    }

    public void run() {
        super.run();
        System.out.println(Thread.currentThread().getName()+":开始消费产品........");

        while(true){
            try {
                Thread.sleep(20);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            clerk.consume();
        }
    }
}
public class ProductTest {
    public static void main(String[] args) {
        Clerk clerk = new Clerk();
        Productor p1 = new Productor(clerk);
        p1.setName("生产者1");

        Consumer c1 = new Consumer(clerk);
        c1.setName("消费者1");

        Consumer c2 = new Consumer(clerk);
        c2.setName("消费者2");

        p1.start();;
        c1.start();
        c2.start();
    }
}
